import React, { useEffect, useRef, useState } from 'react';
import { Card, Tabs, Empty, Spin, Button, Space, Tag, Select, Slider, theme } from 'antd';
import {
  FullscreenOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  ExpandOutlined,
  CompressOutlined
} from '@ant-design/icons';
import cytoscape from 'cytoscape';
// @ts-ignore
import dagre from 'cytoscape-dagre';
import { getLineageThemeConfig, getCytoscapeStyles, NODE_COLORS } from '../utils/lineageTheme';

const { Option } = Select;

interface LineageNode {
  id: string;
  label: string;
  type: string;
}

interface LineageEdge {
  source: string;
  target: string;
  type: string;
  sql_index: number;
}

interface LineageGraphData {
  nodes: LineageNode[];
  edges: LineageEdge[];
  connectors: string[];
}

interface CytoscapeLineageGraphProps {
  data: LineageGraphData | null;
  loading?: boolean;
}

// 节点类型颜色配置已移至 lineageTheme.ts

// 布局选项
const LAYOUT_OPTIONS = [
  { value: 'dagre', label: '层次布局 (Dagre)' },
  { value: 'breadthfirst', label: '广度优先' },
  { value: 'circle', label: '圆形布局' },
  { value: 'concentric', label: '同心圆' },
  { value: 'grid', label: '网格布局' },
  { value: 'cose', label: '力导向布局' }
];

const CytoscapeLineageGraph: React.FC<CytoscapeLineageGraphProps> = ({ data, loading }) => {
  const { token } = theme.useToken();
  const themeConfig = getLineageThemeConfig(token);
  const [activeTab, setActiveTab] = useState<string>('0');
  const [graphGroups, setGraphGroups] = useState<Array<{
    key: string;
    title: string;
    nodes: LineageNode[];
    edges: LineageEdge[];
  }>>([]);
  const [selectedLayout, setSelectedLayout] = useState('dagre');
  const [nodeSize, setNodeSize] = useState(60);
  const [isFullscreen, setIsFullscreen] = useState(false);

  const cyRef = useRef<cytoscape.Core | null>(null);
  const containerRefs = useRef<Record<string, HTMLDivElement | null>>({});

  // 注册 Dagre 布局
  useEffect(() => {
    cytoscape.use(dagre);
  }, []);

  // 分组数据血缘图
  const groupLineageData = (lineageData: LineageGraphData) => {
    if (!lineageData.nodes.length) return [];

    // 使用连通分量算法分组
    const nodeGroups: string[][] = [];
    const visited = new Set<string>();
    const adjacencyList = new Map<string, Set<string>>();

    // 构建邻接表
    lineageData.nodes.forEach(node => {
      adjacencyList.set(node.id, new Set());
    });

    lineageData.edges.forEach(edge => {
      adjacencyList.get(edge.source)?.add(edge.target);
      adjacencyList.get(edge.target)?.add(edge.source);
    });

    // DFS查找连通分量
    const dfs = (nodeId: string, currentGroup: string[]) => {
      if (visited.has(nodeId)) return;
      visited.add(nodeId);
      currentGroup.push(nodeId);
      
      adjacencyList.get(nodeId)?.forEach(neighbor => {
        if (!visited.has(neighbor)) {
          dfs(neighbor, currentGroup);
        }
      });
    };

    // 找到所有连通分量
    lineageData.nodes.forEach(node => {
      if (!visited.has(node.id)) {
        const group: string[] = [];
        dfs(node.id, group);
        if (group.length > 1) { // 只保留有连接的组
          nodeGroups.push(group);
        }
      }
    });

    // 为每个组创建图数据
    const groups = nodeGroups.map((group, index) => {
      const groupNodes = lineageData.nodes.filter(node => group.includes(node.id));
      const groupEdges = lineageData.edges.filter(edge => 
        group.includes(edge.source) && group.includes(edge.target)
      );

      return {
        key: index.toString(),
        title: `数据血缘图 ${index + 1} (${groupNodes.length} 个节点)`,
        nodes: groupNodes,
        edges: groupEdges
      };
    });

    return groups;
  };

  // 处理数据变化
  useEffect(() => {
    if (data && data.nodes.length > 0) {
      const groups = groupLineageData(data);
      setGraphGroups(groups);
      if (groups.length > 0) {
        setActiveTab('0');
      }
    } else {
      setGraphGroups([]);
    }
  }, [data]);

  // 创建Cytoscape实例
  const createCytoscapeGraph = (nodes: LineageNode[], edges: LineageEdge[], tabKey: string) => {
    const container = containerRefs.current[tabKey];
    if (!container) return;

    // 清理现有实例
    if (cyRef.current) {
      cyRef.current.destroy();
    }

    // 转换节点数据
    const cytoscapeNodes = nodes.map(node => ({
      data: {
        id: node.id,
        label: node.label,
        type: node.type,
        color: NODE_COLORS[node.type as keyof typeof NODE_COLORS] || NODE_COLORS.unknown_table
      }
    }));

    // 转换边数据
    const cytoscapeEdges = edges.map((edge, index) => ({
      data: {
        id: `edge-${index}`,
        source: edge.source,
        target: edge.target,
        type: edge.type,
        label: edge.type === 'data_transformation' ? '数据转换' : edge.type
      }
    }));

    // 创建Cytoscape实例
    cyRef.current = cytoscape({
      container: container,
      elements: [...cytoscapeNodes, ...cytoscapeEdges],
      style: getCytoscapeStyles(themeConfig, nodeSize),
      layout: {
        name: selectedLayout,
        directed: true,
        padding: 50,
        spacingFactor: 1.5,
        nodeDimensionsIncludeLabels: true,
        animate: true,
        animationDuration: 500
      }
    });

    // 添加事件监听器
    cyRef.current.on('tap', 'node', (event) => {
      const node = event.target;
      const connectedEdges = node.connectedEdges();
      const connectedNodes = connectedEdges.connectedNodes();

      // 清除之前的高亮
      cyRef.current?.elements().removeClass('highlighted dimmed');

      // 高亮相关节点和边
      node.addClass('highlighted');
      connectedNodes.addClass('highlighted');
      connectedEdges.addClass('highlighted');

      // 使其他元素变暗
      cyRef.current?.elements().not(node.union(connectedNodes).union(connectedEdges)).addClass('dimmed');
    });

    // 点击空白区域清除高亮
    cyRef.current.on('tap', (event) => {
      if (event.target === cyRef.current) {
        cyRef.current?.elements().removeClass('highlighted dimmed');
      }
    });

    // 启用拖拽
    cyRef.current.autoungrabify(false);
  };

  // 当活动标签页或布局改变时重新创建图
  useEffect(() => {
    const currentGroup = graphGroups.find(g => g.key === activeTab);
    if (currentGroup) {
      createCytoscapeGraph(currentGroup.nodes, currentGroup.edges, activeTab);
    }
  }, [activeTab, graphGroups, selectedLayout, nodeSize]);

  // 布局控制函数
  const handleLayoutChange = (layout: string) => {
    setSelectedLayout(layout);
  };

  const handleZoomIn = () => {
    cyRef.current?.zoom(cyRef.current.zoom() * 1.2);
  };

  const handleZoomOut = () => {
    cyRef.current?.zoom(cyRef.current.zoom() * 0.8);
  };

  const handleResetZoom = () => {
    cyRef.current?.fit();
  };

  const handleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  if (loading) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>正在生成数据血缘图...</div>
        </div>
      </Card>
    );
  }

  if (!data || graphGroups.length === 0) {
    return (
      <Card>
        <Empty 
          description="暂无数据血缘图"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </Card>
    );
  }

  return (
    <div style={{ position: isFullscreen ? 'fixed' : 'relative', 
                  top: isFullscreen ? 0 : 'auto',
                  left: isFullscreen ? 0 : 'auto',
                  width: isFullscreen ? '100vw' : '100%',
                  height: isFullscreen ? '100vh' : 'auto',
                  zIndex: isFullscreen ? 9999 : 'auto',
                  backgroundColor: isFullscreen ? token.colorBgContainer : 'transparent' }}>
      <Card 
        title="数据血缘图 (Cytoscape.js)"
        extra={
          <Space wrap>
            <Select
              value={selectedLayout}
              onChange={handleLayoutChange}
              style={{ width: 150 }}
              size="small"
            >
              {LAYOUT_OPTIONS.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
            
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: '12px' }}>节点大小:</span>
              <Slider
                min={40}
                max={100}
                value={nodeSize}
                onChange={setNodeSize}
                style={{ width: 80 }}
                size="small"
              />
            </div>

            <Button icon={<ZoomInOutlined />} onClick={handleZoomIn} size="small">
              放大
            </Button>
            <Button icon={<ZoomOutOutlined />} onClick={handleZoomOut} size="small">
              缩小
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleResetZoom} size="small">
              适应窗口
            </Button>
            <Button 
              icon={isFullscreen ? <CompressOutlined /> : <ExpandOutlined />} 
              onClick={handleFullscreen} 
              size="small"
            >
              {isFullscreen ? '退出全屏' : '全屏'}
            </Button>
          </Space>
        }
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={graphGroups.map(group => ({
            key: group.key,
            label: group.title,
            children: (
              <div>
                <div
                  ref={(el) => {
                    if (el) {
                      containerRefs.current[group.key] = el;
                    }
                  }}
                  style={{
                    width: '100%',
                    height: isFullscreen ? 'calc(100vh - 120px)' : '600px',
                    border: `1px solid ${token.colorBorder}`,
                    borderRadius: '6px',
                    backgroundColor: token.colorBgContainer
                  }}
                />

                {/* 数据流向说明 */}
                {group.edges.length > 0 && (
                  <div style={{ marginTop: '16px', padding: '16px', backgroundColor: token.colorBgContainer, borderRadius: '8px' }}>
                    <h4>数据流向关系：</h4>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                      {group.edges.slice(0, 10).map((edge, index) => (
                        <Tag key={index} color="blue">
                          {edge.source} → {edge.target}
                        </Tag>
                      ))}
                      {group.edges.length > 10 && (
                        <Tag>... 还有 {group.edges.length - 10} 个连接</Tag>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )
          }))}
        />

        {/* 图例 */}
        <div style={{ marginTop: 16, padding: '16px', backgroundColor: token.colorFillQuaternary, borderRadius: '8px' }}>
          <h4>节点类型说明：</h4>
          <Space wrap>
            {Object.entries(NODE_COLORS).map(([type, color]) => (
              <Tag key={type} color={color}>
                {type.replace('_', ' ')}
              </Tag>
            ))}
          </Space>
          <div style={{ marginTop: 8, fontSize: '12px', color: '#666' }}>
            💡 提示：点击节点可高亮相关连接，拖拽节点可调整位置，使用工具栏控制布局和缩放
          </div>
        </div>
      </Card>
    </div>
  );
};

export default CytoscapeLineageGraph;
